/**
 * 描述: 组织机构
 * 日期：2019-07-24
 */

(function(KIT, RES) {
  var __NAME = "机构";

  var URL_ROOT = RES.URL_ROOT + "/group",
    URL_FIND_BY_ID = URL_ROOT + "/getGroupById",
    URL_SAVE = URL_ROOT + "/saveGroup",
    URL_REMOVE = URL_ROOT + "/deleteGroupById",
    URL_GET_TREE = URL_ROOT + "/getGroupsTree";

  //region private

  function _getDvs() {
    return rapid("#frmGroupView").dataview();
  }

  var _initEditWindow = function() {
    rapid("#frmGroupView").dataview({
      colSize: 2,
      paramFields: ["id", "pid"],
      fields: [{
        title: "名称", name: "name", editor: {
          validator: {
            rules: {required: true, maxlength: 50}
          }
        }
      }, {
        title: "编号", name: "code", editor: {
          validator: {
            rules: {required: true, maxlength: 50}
          }
        }
      }, {
        title: "上级名称", name: "pname"
      }, {
        title: "上级编号", name: "pcode"
      }, {
        title: "状态", name: "enabled_ch", editor: {
          name: "enabled", type: "radiolist", defaultValue: 1,
          dataSource: RES.ARR_STATE
        }
      }, {
        title: "锁定", name: "locked_ch", editor: {
          name: "locked", type: "radiolist", defaultValue: 1,
          dataSource: RES.ARR_WHETHER
        }
      }, {
        title: "备注", name: "note", editor: true, colspan: 2
      }]
    });
  };
  
  var _groupTree = function(options) {
    if(arguments.length === 1) {
      return $("#groupTree").g_jstree(rapid.nvl(options, {}));
    }
    return $("#groupTree").g_jstree();
  };

  //初始化组树
  var _initTree = function() {
    _groupTree({
      data: {
        url: URL_GET_TREE
      },
      onselected: function(element, inst, $node) {
        _clearFormBtn();
        _getDvs().reset();
        _changeView(false, true);

        var id = $node.id;

        if(rapid(".group-root").hasClass("group-root-clicked")) {
          rapid(".group-root").removeClass("group-root-clicked");
        }

        rapid.get({
          url: URL_FIND_BY_ID,
          data: "groupId=" + id,
          success: function(data) {
            rapid(".inner-form-title").html(__NAME + "维护");

            _getDvs().bind(data);
            rapid(".inner-form-button").html(FORM_BUTTONS.createAddBtn());
          }
        });
      }
    });
  };

  //初始化按钮
  var _initBtn = function() {
    rapid(".group-root").on("click", function() {
      if(!rapid(this).hasClass("group-root-clicked")) {
        rapid(this).addClass("group-root-clicked");

        rapid(".group-leaf a.jstree-clicked").removeClass("jstree-clicked");
        _changeView(true, false);

        _getDvs().reset();
      }
    });

    //组管理节点添加组
    rapid("#btnAddGroup").on("click", function() {
      _clearFormBtn();
      _changeView(false, false);
      rapid(".inner-form-title").html("添加" + __NAME);
      _getDvs().ui("pname").val("此项为顶级");
      _getDvs().ui("pcode").val("此项为顶级");

      var btns = FORM_BUTTONS.createEditBtn();
      rapid(".inner-form-button").html(btns);

    });

    //添加组
    rapid(".inner-form-button").on("click", ".innerAddGroup", function() {
      _clearFormBtn();
      _changeView(false, false);

      var __dv = _getDvs(),
        data = rapid.nvl(__dv.serializeJson(), {});
      __dv.tag("last", data);

      __dv.reset();
      __dv.bind({id: null, pid: data.id, pname: data.name, pcode: data.code});
      rapid(".inner-form-title").html("添加" + __NAME);

      var btns = FORM_BUTTONS.createEditBtn();
      rapid(".inner-form-button").html(btns);
    });

    //修改
    rapid(".inner-form-button").on("click", ".innerEdit", function() {
      _clearFormBtn();
      _changeView(false, false);

      rapid(".inner-form-title").html("修改" + __NAME);

      var btns = FORM_BUTTONS.createEditBtn();
      rapid(".inner-form-button").html(btns);
    });

    //删除
    rapid(".inner-form-button").on("click", ".innerDel", function(e, rs) {

      var id = _groupTree().getselected().id;
      if(!rapid.isEmpty(id)) {
        rapid.confirm("当前操作会同时删除相关联的子级数据，确定要删除吗？", function(e) {
          if(!e) {
            return;
          }
          rapid.post({
            url: URL_REMOVE,
            data: "groupId=" + id,
            success: function(result) {
              if(!rapid(".group-root").hasClass("group-root-clicked")) {
                rapid(".group-root").addClass("group-root-clicked");
              }

              rapid(".group-leaf a.jstree-clicked").removeClass("jstree-clicked");
              _getDvs().reset();
              _clearFormBtn();
              _changeView(true, false);

              _groupTree().refresh();
              rapid.success();
            }
          });
        });
      }
    });

    //保存
    rapid(".inner-form-button").on("click", ".innerSave", function(e) {

      if(!_getDvs().valid()) {
        return;
      }
      rapid.confirm("确定要保存吗？", function(e) {
        if(!e) {
          return;
        }
        var edit = _getDvs().serializeJson();
        rapid.post({
          url: URL_SAVE,
          data: edit,
          success: function(result) {
            if(result == -1) {
              rapid.error("编号重复！");
              return false;
            }
            if(result == -2) {
              rapid.error("名称重复！");
              return false;
            }

            if(result == 0) {
              rapid.error();
              return false;
            }

            _renderGroupForm();

            _groupTree().refresh();
            rapid.success();
          }
        });
      });
    });

    //取消
    rapid(".inner-form-button").on("click", ".innerCancel", function() {
      _renderGroupForm();
    });
  };

  //初始化单选按钮

  //表单按钮
  var FORM_BUTTONS = {
    innerAddGroup: function() {
      //添加组
      return KIT.html.button({
        cssClass: "innerAddGroup",
        style: 1,
        text: "添加" + __NAME
      });
    },
    innerEdit: function() {
      //修改
      return KIT.html.editButton({cssClass: "innerEdit"});
    },
    innerDel: function() {
      //删除
      return KIT.html.removeButton({cssClass: "innerDel"});
    },
    innerSave: function() {
      //保存
      return KIT.html.saveButton({cssClass: "innerSave"});
    },
    innerCancel: function() {
      //取消
      return KIT.html.cancelButton({cssClass: "innerCancel"});
    },
    createAddBtn: function() {
      //创建添加所含按钮
      return this.innerAddGroup() + this.innerEdit() + this.innerDel();
    },
    createEditBtn: function() {
      //创建编辑所含按钮
      return this.innerSave() + this.innerCancel();
    }
  };

  //清空表单按钮
  var _clearFormBtn = function() {
    rapid(".inner-form-button").html("");
  };

  //判断视图样式
  var _jdugeClass = function(R_elm, removeClass, addClass) {
    R_elm.removeClass(removeClass);
    if(!R_elm.hasClass(addClass)) {
      R_elm.addClass(addClass);
    }
  };

  //切换视图
  var _changeView = function(b, v) {
    var R_button = rapid(".inner-button"),
      R_form = rapid(".inner-form");

    if(b) {
      //组管理视图
      _jdugeClass(R_form, "inner-block", "inner-none");
      _jdugeClass(R_button, "inner-none", "inner-inline");
      _getDvs().reset();
    } else {
      if(v) {
        //查看视图
        _jdugeClass(R_button, "inner-inline", "inner-none");
        _jdugeClass(R_form, "inner-none", "inner-block");
        _getDvs().readonly(true);
      } else {
        //编辑视图
        _getDvs().readonly(false);
        _jdugeClass(R_button, "inner-inline", "inner-none");
        _jdugeClass(R_form, "inner-none", "inner-block");
      }
    }
  };

  //绘制组表单
  var _renderGroupForm = function() {
    _clearFormBtn();

    var bo = false;
    var __dv = _getDvs();
    var pid = __dv.ui("pid").val();

    if(rapid.isEmpty(__dv.ui("id").val())) {
      //新增数据

      __dv.bind(__dv.tag("last")).tag("last", null);

      if(rapid.isEmpty(pid)) {
        //组管理节点新增数据
        bo = true;
        _changeView(true, false);
      } else {
        if(pid == "0") {
          //根节点新增数据
          _changeView(false, true);
        } else {
          //子节点新增数据
          _changeView(false, true);
        }
      }

    } else {
      //修改数据
      if(pid == "0") {
        //根节点修改数据
        _changeView(false, true);
      } else {
        //子节点修改数据
        _changeView(false, true);
      }
    }

    var btns = FORM_BUTTONS.createAddBtn();
    if(!bo) {
      rapid(".inner-form-title").html(__NAME + "维护");
    }

    rapid(".inner-form-button").html(btns);
  };

  //调整页面高度
  var _resize = function() {
    var bw = rapid(window).width();
    var bh = rapid(window).height() - 30;

    var colLeft = rapid(".group-col-left");
    var colRight = rapid(".group-col-right");

    colLeft.height(bh);
    colRight.height(bh);

    if(colLeft.width() + colRight.width() >= bw) {
      colLeft.addClass("col-resize");
    } else {
      colLeft.removeClass("col-resize");
    }

    var rw = colRight.width();
    var rh = colRight.height();

    var innerButton = rapid(".inner-button");
    var iw = innerButton.width();
    var ih = innerButton.height();

    var th = (rh - ih) / 2, tw = 15;
    if(rw > iw) {
      tw = (rw - iw) / 2;
    }

    innerButton.attr("style", "position:absolute; top:" + th + "px; left:" + tw + "px");
  };

  //endregion

  rapid.Page.create()(function() {
    _resize();
    _initEditWindow();
    _initTree();
    _initBtn();

    var rt;
    rapid(window).on("resize", function() {
      clearTimeout(rt);
      rt = setTimeout(_resize, 150);
    });
  }).init();

})(rapid.kit, rapid.res);
